﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Core.Message.Entities;
using Core.ExceptionHandling;
using Core.Controls.Message;
using vHCS.HR.Business;
using vHCS.HR.Entities;
using vHCS.LS.Business;
using Telerik.Web.UI;
using Core.Common.Session;
using System.IO;
using System.Configuration;
using vHCS.K2App.Shared;



namespace vHCS.K2App.MdlK2
{
    public partial class HR_PopAddNewRotationHR1 : Core.NTier.UserInterface.BaseFormNotPer
    {
        #region Property

        protected string trvOrgChartClientId
        {
            get
            {
                try
                {
                    Control ctrlOrgchart = this.cboOrgChart.Items[0].FindControl("trvOrgChart");
                    return ctrlOrgchart.ClientID;
                }
                catch (Exception ex)
                {
                    AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                    MessageBox.Show(message);
                }
                return string.Empty;
            }
        }

        protected string trvProChartClientId
        {
            get
            {
                try
                {

                    Control ctrlProchart = this.cboProChart.Items[0].FindControl("trvProChart");
                    return ctrlProchart.ClientID;

                }
                catch (Exception ex)
                {
                    AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                    MessageBox.Show(message);
                }
                return string.Empty;
            }
        }

        protected string trvMgtChartClientId
        {
            get
            {
                try
                {
                    Control ctrlMgtchart = this.cboMgtChart.Items[0].FindControl("trvMgtChart");
                    return ctrlMgtchart.ClientID;
                }
                catch (Exception ex)
                {
                    AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                    MessageBox.Show(message);
                }
                return string.Empty;
            }
        }
        #endregion

        #region Const
        private const string _TargetFolder = "UploadFile/WorkingRecord";
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "CheckDecision", "ChangeSalary();", true);
                ClientScript.RegisterStartupScript(Page.GetType(), "LoadMaximize", "LoadMaximize();", true);
              
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        #region Form Events
        /// <summary>
        /// Hàm xử lý sự kiện khi thay đổi giá trị của cấp bậc
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cboJobLevel_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            try
            {
                /* Load JobTitle theo JobChart và cấp bậc (đã bỏ)
                PopulateJobTitle();
                 */

                //Load loại nhân viên theo cấp bậc
                LS_JobLevelBL joblevel_bl = new LS_JobLevelBL();
                LS_JobLevelCollection joblevel_cl = new LS_JobLevelCollection();
                joblevel_bl = joblevel_cl.SelectByID(Convert.ToInt64(cboJobLevel.SelectedValue == "" ? "0" : cboJobLevel.SelectedValue));

                if (joblevel_bl.DTO != null)
                {
                    LS_EmpTypeBL emptype_bl = new LS_EmpTypeBL();
                    LS_EmpTypeCollection emptype_cl = new LS_EmpTypeCollection();
                    emptype_bl = emptype_cl.SelectByID(joblevel_bl.LSEmpTypeID);

                    if (emptype_bl.DTO != null)
                    {
                        txtLoainhanvien_Now.Text = (SessionManager.LanguageID == "VN" || string.IsNullOrEmpty(emptype_bl.NameEN)) ? emptype_bl.NameVN : emptype_bl.NameEN;
                        hdfEmptype.Value = emptype_bl.LSEmpTypeID.ToString();
                    }
                    else
                    {
                        txtLoainhanvien_Now.Text = null;
                        hdfEmptype.Value = null;
                    }
                }
                else
                {
                    txtLoainhanvien_Now.Text = null;
                    hdfEmptype.Value = null;
                }

            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// Load danh sách cho cboJobTitle
        /// </summary>
        protected void PopulateJobTitle()
        {
            try
            {
                long jobLevelId = 0;
                HIE_JobChartNode selectedNode = new HIE_JobChartNode();
                long.TryParse(this.cboJobLevel.SelectedValue, out jobLevelId);

                //Nếu cơ cấu quản lý không có giá trị thì chọn cơ cấu chuyên môn
                if (string.IsNullOrEmpty(cboMgtChart.SelectedValue)
                    || cboMgtChart.SelectedValue == HIE_HierarchyCollection.JobChartNullNodeValue)
                    selectedNode = HIE_HierarchyCollection.ParseJobChartNode(cboProChart.SelectedValue);
                else
                    selectedNode = HIE_HierarchyCollection.ParseJobChartNode(this.cboMgtChart.SelectedValue);

                this.dtsJobTitle.SelectParameters["jobLevelId"].DefaultValue = jobLevelId.ToString();
                this.dtsJobTitle.SelectParameters["jobFamilyId"].DefaultValue = selectedNode.JobFamilyId.ToString();
                this.dtsJobTitle.SelectParameters["jobGroupId"].DefaultValue = selectedNode.JobGroupId.ToString();
                this.dtsJobTitle.SelectParameters["subGroupId"].DefaultValue = selectedNode.SubGroupId.ToString();
                this.dtsJobTitle.CacheClear();
                this.cboJobTitle.DataBind();

            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        //protected void cboChangeType_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        //{
        //    try
        //    {
        //        //long v_lTypeId = 0;
        //        //long.TryParse(this.cboChangeType.SelectedValue, out v_lTypeId);
        //        //if (v_lTypeId <= 0) v_lTypeId = -1;
        //        //this.dtsChangeForm.SelectParameters["p_lChangeTypeId"].DefaultValue = v_lTypeId.ToString();
        //        //this.cboChangeForm.DataBind();
        //    }
        //    catch (Exception ex)
        //    {
        //        AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
        //        MessageBox.Show(message);
        //    }
        //}

        protected void HR_ctrEmpHeader_OnUserChanged(object sender, EventArgs e)
        {
            try
            {
                LoadWorkingRecordLast();
                hdfEmpID.Value = ctrEmpInfo.EmployeeId.ToString();

                //Lấy ngày vào làm của nhân viên
                HR_EmpBL bl = new HR_EmpBL();
                HR_EmpCollection cl = new HR_EmpCollection();
                bl = cl.SelectByID(ctrEmpInfo.EmployeeId);

                dpkNgayvaocty.SelectedDate = bl.JoinDate;

            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }
        #endregion

        #region Functions

        #region Tạo đường dẫn đến file
        /// <summary>
        /// Author: DungN2, create date: 28/02/2011
        /// Tạo đường dẫn đến file
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="extension"></param>
        /// <param name="counter"></param>
        /// <returns></returns>
        public string ReturnPath(string filename, string extension, int counter)
        {
            string path = "";
            try
            {
                if (counter <= 0)
                {
                    path = Server.MapPath("../" + _TargetFolder + "/" + filename + extension);
                }
                else
                {
                    path = Server.MapPath("../" + _TargetFolder + "/" + filename + counter.ToString() + extension);
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
            return path;
        }
        #endregion

        #region Phương thức Upload File
        /// <summary>
        /// Author: DungN2, create date: 28/02/2011
        /// Phương thức Upload File
        /// </summary>
        public string UploadFile()
        {
            string filename = "";
            try
            {
                foreach (UploadedFile uploadfile in uplAttatchFile.UploadedFiles)
                {
                    int counter = 0;
                    filename = uploadfile.GetName();
                    string path = ReturnPath(uploadfile.GetNameWithoutExtension(), uploadfile.GetExtension(), 0);
                    while (File.Exists(path))//Kiểm tra file có tồn tại chưa nếu tồn tại thì thêm số thứ tự file vào tên file
                    {
                        counter++;
                        path = ReturnPath(uploadfile.GetNameWithoutExtension(), uploadfile.GetExtension(), counter);
                        filename = uploadfile.GetNameWithoutExtension() + counter.ToString() + uploadfile.GetExtension();
                    }

                    uploadfile.SaveAs(path);
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
            return filename;
        }
        #endregion

        /// <summary>
        /// Gán thông tin JobRole vào combo
        /// </summary>
        /// <param name="arrayjobrole"></param>
        public void LoadJobRole(string arrayjobrole)
        {
            try
            {
                string[] str_list = arrayjobrole.Split(';');
                foreach (string str_jobrole in str_list)
                {
                    long jobrole = 0;
                    long.TryParse(str_jobrole, out jobrole);
                    if (jobrole > 0)
                    {
                        cboJobRole.SelectedValue = jobrole.ToString();
                        RadComboBoxItem item = cboJobRole.SelectedItem;
                        CheckBox chk = (CheckBox)item.FindControl("chkJobRole");
                        if (chk != null)
                            chk.Checked = true;
                    }
                }

                SetComboValue(cboJobRole, null, true);
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// DungN2
        /// Get combo jobchart và cấp bậc theo jobtitle
        /// </summary>
        /// <param name="jobtitle">mã jobtitle</param>
        /// <param name="joblevel">mã joblevel, được sử dụng khi edit mẫu tin</param>
        public void PopulateJobTitle(long jobtitle)
        {
            try
            {
                dtsProChart.SelectParameters["Jobtitle"].DefaultValue = jobtitle.ToString();
                RadTreeView treeviewpro = (RadTreeView)cboProChart.Items[0].FindControl("trvProChart");
                treeviewpro.DataBind();

                dtsMgtChart.SelectParameters["Jobtitle"].DefaultValue = jobtitle.ToString();
                RadTreeView treeviewmgt = (RadTreeView)cboMgtChart.Items[0].FindControl("trvMgtChart");
                treeviewmgt.DataBind();

                dtsJobLevel.SelectParameters["jobtitle"].DefaultValue = jobtitle.ToString();
                cboJobLevel.DataSourceID = dtsJobLevel.ID;
                cboJobLevel.DataBind();

                if (treeviewpro.IsEmpty)
                {
                    lblCanhBaoProChart.Visible = true;
                }
                else
                    lblCanhBaoProChart.Visible = false;
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// Tách mảng giá trị Jobrole
        /// </summary>
        /// <param name="listid">chuỗi chứa mảng giá trị jobrole</param>
        /// <returns></returns>
        public List<Int64> ParseJob(string listid)
        {
            List<Int64> result = new List<Int64>();
            try
            {
                if (!string.IsNullOrEmpty(listid.Trim(';')))
                {
                    string[] str_listid = listid.Split(';');
                    foreach (string id in str_listid)
                    {
                        result.Add(Convert.ToInt64(id));
                    }
                }
            }
            catch (Exception ex)
            {
                DataAccessExceptionHandler.HandleException(ex);
            }
            return result;
        }

        /// <summary>
        /// DungN2
        /// Lấy thông tin WR sau cùng của nhân viên
        /// </summary>
        public void LoadWorkingRecordLast()
        {
            try
            {
                if (ctrEmpInfo.EmployeeId > 0)
                {
                    HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();
                    HR_WorkingRecordBL bl = new HR_WorkingRecordBL();
                    bl = cl.SelectLastWRByEmpID(ctrEmpInfo.EmployeeId);

                    if (bl.DTO != null)
                    {
                        dtsComboTrocap.SelectParameters["workingrecordid"].DefaultValue = bl.WorkingRecordID.ToString();
                        dtsComboTrocap.DataBind();

                        //Load VP làm việc
                        LS_WorkPlaceCollection cl_workplace = new LS_WorkPlaceCollection();
                        LS_WorkPlaceBL bl_workplace = new LS_WorkPlaceBL();
                        bl_workplace = cl_workplace.SelectByID(bl.LSWorkPlaceID);
                        if (bl_workplace.DTO != null)
                            txtOffice.Text = (SessionManager.LanguageID == "VN" || bl_workplace.NameEN == "") ? bl_workplace.NameVN : bl_workplace.NameEN;
                        SetComboValue(cboOffice, bl.LSWorkPlaceID, true);

                        //Load cơ cấu tổ chức
                        txtCocautochuc.Text = cl.SelectOrgChartName(bl.WorkingRecordID);
                        txtOrgchartID.Text = bl.HierarchyId.ToString();
                        rttOrgChart.Text = txtCocautochuc.Text.Trim();
                        //Gán cây cơ cấu tổ chức
                        cboOrgChart.Items.Clear();
                        RadComboBoxItem item_orgchart = new RadComboBoxItem(txtCocautochuc.Text.Trim(), bl.HierarchyId.ToString());
                        cboOrgChart.Items.Insert(0, item_orgchart);
                        cboOrgChart.SelectedIndex = 0;
                        rttOrgChart_input.Text = txtCocautochuc.Text.Trim();

                        //Load chức vụ
                        LS_JobTitleBL bl_title = new LS_JobTitleBL();
                        LS_JobTitleCollection cl_title = new LS_JobTitleCollection();
                        bl_title = cl_title.SelectByID(bl.JobTitleID);
                        if (bl_title.DTO != null)
                            txtChucvu.Text = (SessionManager.LanguageID == "VN" || bl_title.NameEN == "") ? bl_title.NameVN : bl_title.NameEN;
                        cboJobTitle.DataBind();
                        SetComboValue(cboJobTitle, dtsJobTitle, "prefix", bl.JobTitleID.ToString());

                        //Load cơ cấu chuyên môn
                        txtCocauchuyenmon.Text = cl.SelectProJobNameFull(bl.WorkingRecordID);
                        rttProChart.Text = txtCocauchuyenmon.Text.Trim();
                        //Gán cây cơ cấu chuyên môn
                        //Load giá trị cho view trong cây cơ cấu chuyên môn
                        RadTreeView treepro = (RadTreeView)cboProChart.Items[0].FindControl("trvProChart");
                        dtsProChart.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + bl.ProSubGroupId.ToString();
                        dtsProChart.SelectParameters["jobtitle"].DefaultValue = bl.JobTitleID.ToString();
                        treepro.DataBind();

                        cboProChart.Items.Clear();
                        string proname = cl.SelectProJobName(bl.WorkingRecordID);
                        RadComboBoxItem item_prochart = new RadComboBoxItem(proname, cl.SelectProJobID(bl.WorkingRecordID));
                        cboProChart.Items.Insert(0, item_prochart);
                        cboProChart.SelectedIndex = 0;
                        rttProChart_input.Text = proname;
                        //ProRanking
                        SetComboValue(cboProRanking, bl.ProRankingId, true);
                        //ProGrade
                        dtsProGrade.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + bl.ProGradeId.ToString();
                        cboProGrade.DataSourceID = dtsProGrade.ID;
                        cboProGrade.DataBind();
                        SetComboValue(cboProGrade, bl.ProGradeId, true);

                        //Load cơ cấu quản lý
                        txtCocauquanly.Text = cl.SelectMgtJobNameFull(bl.WorkingRecordID);
                        rttMgtChart.Text = txtCocauquanly.Text.Trim();
                        //Gán cây cơ cấu quản lý
                        //Load giá trị cho treeview trong cây cơ cấu quản lý
                        RadTreeView treemgt = (RadTreeView)cboMgtChart.Items[0].FindControl("trvMgtChart");
                        dtsMgtChart.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + bl.MgtSubGroupId.ToString();
                        dtsMgtChart.SelectParameters["jobtitle"].DefaultValue = bl.JobTitleID.ToString();
                        treemgt.DataBind();

                        cboMgtChart.Items.Clear();
                        string mgtname = cl.SelectMgtJobName(bl.HierarchyId);
                        RadComboBoxItem item_mgtchart = new RadComboBoxItem(mgtname, cl.SelectMgtJobID(bl.WorkingRecordID));
                        cboMgtChart.Items.Insert(0, item_mgtchart);
                        cboMgtChart.SelectedIndex = 0;
                        rttMgtChart_input.Text = mgtname;
                        //MgtRanking
                        SetComboValue(cboMgtRaking, bl.MgtRankingId, true);
                        //MgtGrade
                        dtsMgtGrade.SelectParameters["prefix"].DefaultValue = "$SelectedValue$" + bl.MgtGradeId.ToString();
                        cboMgtGrade.DataSourceID = dtsMgtGrade.ID;
                        cboMgtGrade.DataBind();
                        SetComboValue(cboMgtGrade, bl.MgtGradeId, true);

                        //Load cấp bậc
                        dtsJobLevel.SelectParameters["p_strPrefix"].DefaultValue = "$SelectedValue$" + bl.LSLevelID.ToString();
                        dtsJobLevel.SelectParameters["jobtitle"].DefaultValue = bl.JobTitleID.ToString();
                        cboJobLevel.DataBind();
                        LS_JobLevelBL bl_joblevel = new LS_JobLevelBL();
                        LS_JobLevelCollection cl_joblevel = new LS_JobLevelCollection();
                        bl_joblevel = cl_joblevel.SelectByID(bl.LSLevelID);
                        if (bl_joblevel.DTO != null)
                            txtCapbac.Text = (SessionManager.LanguageID == "VN" || bl_joblevel.NameEN == "") ? bl_joblevel.NameVN : bl_joblevel.NameEN;
                        SetComboValue(cboJobLevel, dtsJobLevel, "p_strPrefix", bl.LSLevelID.ToString());

                        cboJobLevel_SelectedIndexChanged(null, null);

                        //Load jobrole
                        txtJobrole.Text = cl.SelectJobRoleName(bl.WorkingRecordID);
                        txtJobroleID.Text = cl.SelectJobRoleID(bl.WorkingRecordID);
                        rttJobRole.Text = txtJobrole.Text.Trim();
                        //Gán jobrole
                        //Gán check cho các checkbox được chọn
                        LoadJobRole(cl.SelectJobRoleID(bl.WorkingRecordID));
                        //Load thông tin ban đầu cho combobox
                        RadComboBoxItem item_jobrole = new RadComboBoxItem(txtJobrole.Text.Trim(), cl.SelectJobRoleID(bl.WorkingRecordID));
                        cboJobRole.Items.Insert(cboJobRole.Items.Count, item_jobrole);
                        cboJobRole.SelectedIndex = cboJobRole.Items.Count - 1;
                        cboJobRole.Items[cboJobRole.Items.Count - 1].Visible = false;
                        rttJobRole_input.Text = txtJobrole.Text.Trim();

                        //Load loại nhân viên
                        LS_EmpTypeBL bl_emptype = new LS_EmpTypeBL();
                        LS_EmpTypeCollection cl_emptype = new LS_EmpTypeCollection();
                        bl_emptype = cl_emptype.SelectByID(bl_joblevel.LSEmpTypeID);
                        if (bl_emptype.DTO != null)
                        {
                            txtLoainhanvien.Text = (SessionManager.LanguageID == "VN" || bl_emptype.NameEN == "") ? bl_emptype.NameVN : bl_emptype.NameEN;
                            hdfEmptype.Value = bl_emptype.LSEmpTypeID.ToString();
                        }

                        txtLeader.Text = cl.ReturnLeader(Convert.ToInt64(cboOrgChart.SelectedValue == "" ? "0" : cboOrgChart.SelectedValue)); 
                        txtLeader_Now.Text = cl.ReturnLeader(Convert.ToInt64(cboOrgChart.SelectedValue == "" ? "0" : cboOrgChart.SelectedValue));

                        HR_EmpCVCollection cl_empcv = new HR_EmpCVCollection();
                        txtNguoibaocao.Text = cl_empcv.GetDisplayNameByUser(string.IsNullOrEmpty(bl.ReportingLine) ? "" : bl.ReportingLine);
                        SetComboValue(cboReportTo, dtsReportTo, "prefix", bl.ReportingLine);

                        txtNguoipheduyet.Text = cl_empcv.GetDisplayNameByUser(string.IsNullOrEmpty(bl.Approver) ? "" : bl.Approver);
                        SetComboValue(cboNguoipheduyet_Now, dtsNguoiPheDuyet, "prefix", bl.Approver);
                        txtNguoimentor.Text = cl_empcv.GetDisplayNameByUser(string.IsNullOrEmpty(bl.Mentor) ? "" : bl.Mentor);
                        SetComboValue(cboNguoimentor_Now, dtsNguoiMentor, "prefix", bl.Mentor);

                        txtGross.Value = bl.GrossSalary;
                        txtLuongcanban.Value = bl.BasisSalary;
                        txtKPI.Value = bl.KPI;
                        txtTrocaptonghop.Value = bl.GeneralSusidies;
                        txtLuongCTV.Value = bl.CollaborationSalary;

                        //Change salary
                        if (chkChangeSalary.Checked)
                        {
                            txtGross_Now.Value = txtGross.Value;
                            txtLuongcanban_Now.Value = txtLuongcanban.Value;
                            txtKPI_Now.Value = txtKPI.Value;
                            txtTrocaptonghop_Now.Value = txtTrocaptonghop.Value;
                            txtLuongCTV_Now.Value = txtLuongCTV.Value;

                            txtGross_Now.Enabled = true;
                            txtLuongcanban_Now.Enabled = true;
                            txtKPI_Now.Enabled = true;
                            txtTrocaptonghop_Now.Enabled = true;
                            txtLuongCTV_Now.Enabled=true;
                        }

                        //Load danh sách trợ cấp
                        dtsTrocap.SelectParameters["workingrecordid"].DefaultValue = bl.WorkingRecordID.ToString();
                        dtgTroCap.DataSourceID = dtsTrocap.ID;
                        dtgTroCap.DataBind();
                    }
                    else
                    {
                        txtOffice.Text = null;
                        txtCocautochuc.Text = null;
                        txtCocauchuyenmon.Text = null;
                        txtCocauquanly.Text = null;
                        txtCapbac.Text = null;
                        txtChucvu.Text = null;
                        txtJobrole.Text = null;
                        txtLoainhanvien.Text = null;
                        txtLeader.Text = null;
                        txtNguoibaocao.Text = null;
                        txtNguoipheduyet.Text = null;
                        txtNguoimentor.Text = null;
                        txtGross.Value = 0;
                        txtLuongcanban.Value = 0;
                        txtKPI.Value = 0;
                        txtTrocaptonghop.Value = 0;
                    }
                }
                else
                    MessageBox.ShowByMessCode("10095");
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// DungN2
        /// Thêm mới JobRole vào WR
        /// </summary>
        public void InsertJobRole()
        {
            try
            {
                HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();
                long workingid = 0;
                long.TryParse(hdfWorkingRecordID.Value, out workingid);
                List<long> listjobrole = new List<long>();

                foreach (RadComboBoxItem item in cboJobRole.Items)
                {
                    CheckBox chk = (CheckBox)item.FindControl("chkJobRole");
                    if (chk.Checked)
                    {
                        listjobrole.Add(Convert.ToInt64(item.Value));
                    }
                }

                if (listjobrole.Count > 0)
                {
                    cl.Delete_JobRole(workingid);
                    cl.InsertJobRole(workingid, listjobrole);
                }

            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// Dungn2
        /// Reset lại các control nhập liệu
        /// </summary>
        public void ResetControl()
        {
            try
            {
                //SetComboValue(cboChangeType, null, true);
                cboChangeForm.DataBind();
                dpkEffectiveDate.SelectedDate = null;
                rbtDecision.SelectedValue = "1";
                txtGhichu.Text = null;
                SetComboValue(cboOffice, null, true);
                cboOrgChart.Items.Clear();
                cboOrgChart.Items.Insert(0, new RadComboBoxItem("", ""));
                cboOrgChart.SelectedIndex = 0;
                cboProChart.Items.Clear();
                cboProChart.Items.Insert(0, new RadComboBoxItem("", ""));
                cboProChart.SelectedIndex = 0;
                cboMgtChart.Items.Clear();
                cboMgtChart.Items.Insert(0, new RadComboBoxItem("", ""));
                cboMgtChart.SelectedIndex = 0;
                SetComboValue(cboProGrade, null, true);
                SetComboValue(cboProRanking, null, true);
                SetComboValue(cboMgtGrade, null, true);
                SetComboValue(cboMgtRaking, null, true);
                SetComboValue(cboJobLevel, null, true);
                cboJobTitle.DataBind();
                SetComboValue(cboJobRole, null, true);
                txtLoainhanvien_Now.Text = null;
                txtLeader_Now.Text = null;
                SetComboValue(cboReportTo, null, true);
                SetComboValue(cboNguoimentor_Now, null, true);
                SetComboValue(cboNguoipheduyet_Now, null, true);
                rbtDuytriquyenhan.SelectedValue = "2";
                chkChangeSalary.Checked = false;
                txtGross_Now.Value = 0;
                txtLuongcanban_Now.Value = 0;
                txtKPI_Now.Value = 0;
                txtTrocaptonghop_Now.Value = 0;
                txtGross_Now.Enabled = false;
                txtLuongcanban_Now.Enabled = false;
                txtKPI_Now.Enabled = false;
                txtTrocaptonghop_Now.Enabled = false;
                dtgTroCap.DataBind();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// DungN2
        /// Cập nhật trợ cấp khác cho WR
        /// </summary>
        public void InsertAllowance()
        {
            try
            {
                HR_WorkingRecord_DependantCollection cl = new HR_WorkingRecord_DependantCollection();
                HR_WorkingRecord_DependantBL bl = new HR_WorkingRecord_DependantBL();
                if (dtgTroCap.Items.Count > 0)
                {
                    foreach (GridDataItem item in dtgTroCap.Items)
                    {
                        RadNumericTextBox txtamount = (RadNumericTextBox)item["Amount"].FindControl("txtAmount");
                        if (txtamount.Value > 0)
                        {
                            //RadComboBox cboComboTrocap = (RadComboBox)item.FindControl("cboTroCap");
                            bl.LSAllowanceID = Convert.ToInt64(item["LSAllowanceID"].Text.Trim());
                            bl.WorkingRecordID = Convert.ToInt64(hdfWorkingRecordID.Value);

                            bl.Amount = Convert.ToDouble(txtamount.Value);
                            bl.CreatedUser = SessionManager.UserDomain;

                            cl.InsertWR(bl);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// DungN2
        /// Lấy mã JobRole từ combo JobRole so sánh nơi đi và nơi đến
        /// true: hợp lệ; false: không hợp lệ
        /// </summary>
        /// <returns></returns>
        public bool CheckIDJobRole()
        {
            try
            {
                string jobroleold = ";" + txtJobroleID.Text + ";";
                foreach (RadComboBoxItem item in cboJobRole.Items)
                {
                    CheckBox chk = (CheckBox)item.FindControl("chkJobRole");
                    if (chk.Checked)
                    {
                        if (jobroleold.Contains(";" + item.Value + ";") == false)
                            return true;
                    }
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
            return false;
        }

        /// <summary>
        /// DungN2
        /// </summary>
        /// <returns>false:nơi đến trùng với nơi đi; true: nơi đến ko trùng với nơi đi</returns>
        public bool CheckNoiDen()
        {
            try
            {
                HR_WorkingRecordBL bl_last = new HR_WorkingRecordBL();
                HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();
                bl_last = cl.SelectLastWRByEmpID(ctrEmpInfo.EmployeeId);

                long lsworkplace = 0;
                long hierachy = 0;
                string proid = "";
                string mgtid = "";
                long levelid = 0;
                long jobtitle = 0;
                //Lấy dữ liệu nơi đi
                if (bl_last.DTO != null)
                {
                    lsworkplace = bl_last.LSWorkPlaceID;
                    hierachy = bl_last.HierarchyId;
                    proid = bl_last.ProJobFamilyId.ToString() + ";" + bl_last.ProJobGroupId.ToString() + ";" + bl_last.ProSubGroupId.ToString();
                    mgtid = bl_last.MgtJobFamilyId.ToString() + ";" + bl_last.MgtJobGroupId.ToString() + ";" + bl_last.MgtSubGroupId.ToString();
                    levelid = bl_last.LSLevelID;
                    jobtitle = bl_last.JobTitleID;
                }

                //Lấy dữ liệu nơi đến
                long lsworkplace_now = 0;
                long.TryParse(cboOffice.SelectedValue, out lsworkplace_now);

                long hierachy_now = 0;
                long.TryParse(cboOrgChart.SelectedValue, out hierachy_now);

                string proid_now = cboProChart.SelectedValue;
                string mgtid_now = cboMgtChart.SelectedValue;

                long levelid_now = 0;
                long.TryParse(cboJobLevel.SelectedValue, out levelid_now);

                long jobtitle_now = 0;
                long.TryParse(cboJobTitle.SelectedValue, out jobtitle_now);

                //Kiểm tra nơi đến có trùng với nơi đi, nếu trùng trả về false
                if (lsworkplace == lsworkplace_now)
                    if (hierachy == hierachy_now)
                        if (proid == proid_now)
                            if (levelid == levelid_now)
                                if (jobtitle == jobtitle_now)
                                    //if(CheckIDJobRole()==false)
                                    if (bl_last.ProRankingId.ToString() == (string.IsNullOrEmpty(cboProRanking.SelectedValue) ? "0" : cboProRanking.SelectedValue))
                                        if (bl_last.ProGradeId.ToString() == (string.IsNullOrEmpty(cboProGrade.SelectedValue) ? "0" : cboProGrade.SelectedValue))
                                            return false;

            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
            return true;
        }

        #endregion

        protected void btnSubmit_Top_Click(object sender, EventArgs e)
        {
            try
            {
                if (ctrEmpInfo.EmployeeId > 0)
                {
                    HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();
                    HR_WorkingRecordBL bl = new HR_WorkingRecordBL();
                    HIE_HierarchyCollection cl_hie = new HIE_HierarchyCollection();

                    //Gán loại hình thức thay đổi
                    bl.LSStatusChangeID = Convert.ToInt64(cboChangeForm.SelectedValue);
                    bl.EmpID = ctrEmpInfo.EmployeeId;
                    bl.FromDate = Convert.ToDateTime(dpkEffectiveDate.SelectedDate);
                    if (rbtDecision.SelectedValue == "1")
                        bl.Decision = true;
                    else
                        bl.Decision = false;

                    //Gán attach file
                    bl.AttachFile = UploadFile();
                    //Gán nơi làm việc
                    bl.LSWorkPlaceID = Convert.ToInt64(cboOffice.SelectedValue);
                    //Gán cơ cấu tổ chức
                    bl.HierarchyId = Convert.ToInt64(cboOrgChart.SelectedValue);

                    //Projob
                    List<Int64> Projob = ParseJob(cboProChart.SelectedValue);
                    if (Projob.Count > 0)
                    {
                        bl.ProJobFamilyId = Projob[0];
                        bl.ProJobGroupId = Projob[1];
                        bl.ProSubGroupId = Projob[2];
                    }
                    bl.ProRankingId = Convert.ToInt64(cboProRanking.SelectedValue == "" ? "0" : cboProRanking.SelectedValue);
                    bl.ProGradeId = Convert.ToInt64(cboProGrade.SelectedValue == "" ? "0" : cboProGrade.SelectedValue);
                    //MgtJob
                    List<Int64> MgtJob = ParseJob(cboMgtChart.SelectedValue);
                    if (MgtJob.Count > 0)
                    {
                        bl.MgtJobFamilyId = MgtJob[0];
                        bl.MgtJobGroupId = MgtJob[1];
                        bl.MgtSubGroupId = MgtJob[2];
                    }
                    bl.MgtRankingId = Convert.ToInt64(cboMgtRaking.SelectedValue == "" ? "0" : cboMgtRaking.SelectedValue);
                    bl.MgtGradeId = Convert.ToInt64(cboMgtGrade.SelectedValue == "" ? "0" : cboMgtGrade.SelectedValue);

                    bl.LSLevelID = Convert.ToInt64(string.IsNullOrEmpty(cboJobLevel.SelectedValue) ? "0" : cboJobLevel.SelectedValue);
                    bl.JobTitleID = Convert.ToInt64(string.IsNullOrEmpty(cboJobTitle.SelectedValue) ? "0" : cboJobTitle.SelectedValue);
                    bl.LSEmpTypeID = Convert.ToInt64(string.IsNullOrEmpty(hdfEmptype.Value) ? "0" : hdfEmptype.Value);
                    bl.Leader = txtLeader_Now.Text.Trim();
                    bl.ReportingLine = cboReportTo.SelectedValue;
                    bl.Approver = cboNguoipheduyet_Now.SelectedValue;
                    bl.Mentor = cboNguoimentor_Now.SelectedValue;
                    bl.Note = txtGhichu.Text.Trim();

                    //Gán có duy tri quyền hạn hay không
                    if (rbtDuytriquyenhan.SelectedValue == "1")
                        bl.IsRemainRight = true;
                    else
                        bl.IsRemainRight = false;
                    bl.IsChangeSalary = chkChangeSalary.Checked;
                    //Nếu có thay đổi lương thì gán mức lương mới
                    if (chkChangeSalary.Checked)
                    {
                        bl.GrossSalary = Convert.ToDouble(txtGross_Now.Value);
                        bl.BasisSalary = Convert.ToDouble(txtLuongcanban_Now.Value);
                        bl.KPI = Convert.ToDouble(txtKPI_Now.Value);
                        bl.GeneralSusidies = Convert.ToDouble(txtTrocaptonghop_Now.Value);
                        bl.CollaborationSalary = Convert.ToDouble(txtLuongCTV_Now.Value);
                    }
                    else //Ngược lại vẫn giữ mức lương cũ
                    {
                        bl.GrossSalary = Convert.ToDouble(txtGross.Value);
                        bl.BasisSalary = Convert.ToDouble(txtLuongcanban.Value);
                        bl.KPI = Convert.ToDouble(txtKPI.Value);
                        bl.GeneralSusidies = Convert.ToDouble(txtTrocaptonghop.Value);
                        bl.CollaborationSalary = Convert.ToDouble(txtLuongCTV.Value);
                    }

                    bl.Status = false;
                    bl.IsWorkingRecord = 0;
                    bl.CreatedUser = SessionManager.UserDomain;

                    HR_WorkingRecordBL bl_checkexists = new HR_WorkingRecordBL();
                    bl_checkexists = cl.SelectByEffectivedate(bl.EmpID, bl.FromDate, 0, 0);//Tìm kiếm có quá trình làm việc trùng ngày hiệu lực được nhập vào
                    bool Checkexits_staffmovement = cl.CheckStaffMovement(bl.EmpID);
                    if (bl_checkexists.DTO == null)
                    {
                        if (Checkexits_staffmovement == true)
                        {
                            if (cl_hie.CheckHierachyLevel(bl.HierarchyId, 3))
                            {
                                hdfWorkingRecordID.Value = cl.Insert(bl).ToString();
                                if (bl.IsChangeSalary)
                                {
                                    InsertAllowance();
                                }
                                InsertJobRole();

                                try
                                {
                                    #region Xử lý K2
                                    //Start K2
                                    K2Collection colK2 = new K2Collection();
                                    HIE_EmpInHierarchyCollection cl_emphie = new HIE_EmpInHierarchyCollection();
                                    string empid = ctrEmpInfo.EmployeeId.ToString();
                                    string workingrecordid = hdfWorkingRecordID.Value;
                                    //Lấy trưởng phòng ban nơi đi
                                    string fromhierarchy = cl_emphie.SelectDeptHie(Convert.ToInt64(string.IsNullOrEmpty(txtOrgchartID.Text) ? "0" : txtOrgchartID.Text)).ToString();
                                    //Lấy trưởng phòng ban nơi đến
                                    string tohierarchy = cl_emphie.SelectDeptHie(Convert.ToInt64(string.IsNullOrEmpty(cboOrgChart.SelectedValue) ? "0" : cboOrgChart.SelectedValue)).ToString();
                                    //Lấy node nơi đến
                                    string hierarchyid = cboOrgChart.SelectedValue;
                                    string NextApproved = colK2.GetLeaderOfHierarchy(Convert.ToInt16(string.IsNullOrEmpty(fromhierarchy) ? "0" : fromhierarchy));

                                    string ApproveLink = ConfigurationManager.AppSettings.Get("LinkWRApprove");
                                    string ViewHistoryLink = ConfigurationManager.AppSettings.Get("LinkStaffMovement") + hdfWorkingRecordID.Value;
                                    //Get thông tin Expire
                                    string ExpireDay = ConfigurationManager.AppSettings.Get("SM_ExpireDay");
                                    string ExpireAlert = ConfigurationManager.AppSettings.Get("SM_ExpireAlert");

                                    #region Lấy thông tin gửi mail next approve
                                    vHCS.SYS.Business.SYS_MailTemplateCollection cl_nextapprove = new vHCS.SYS.Business.SYS_MailTemplateCollection();
                                    SYS.Entities.SYS_MailTemplateDTO dto_mail = new SYS.Entities.SYS_MailTemplateDTO();
                                    dto_mail = cl_nextapprove.GetMailContentWithSignature("WR_NextApprove","K2-Signature");
                                    string MailContent_NextApprove = "";
                                    string MailSubject_NextApprove = "";

                                    if (dto_mail != null)
                                    {
                                        MailContent_NextApprove = dto_mail.ContentVN;
                                        MailContent_NextApprove = MailContent_NextApprove.Replace("$Creator$", SessionManager.UserDomain);
                                        MailContent_NextApprove = MailContent_NextApprove.Replace("$url$", ConfigurationManager.AppSettings.Get("LinkWRApprove_Old"));
                                        MailSubject_NextApprove = dto_mail.TitleVN;
                                        MailSubject_NextApprove = MailSubject_NextApprove.Replace("$Creator$", SessionManager.UserDomain);
                                    }

                                    //Lấy email người gửi đến
                                    vHCS.SYS.Business.SYS_UsersCollection cl_user = new vHCS.SYS.Business.SYS_UsersCollection();
                                    vHCS.SYS.Business.SYS_UsersBL bl_user = new vHCS.SYS.Business.SYS_UsersBL();
                                    bl_user = cl_user.FindById_BL(NextApproved);
                                    string email_nextapprove = "";
                                    if (bl_user.DTO != null)
                                    {
                                        email_nextapprove = bl_user.Email;
                                    }
                                    #endregion

                                    #region Lấy thông tin gửi mail request
                                    dto_mail = cl_nextapprove.GetMailContentWithSignature("WR_Request", "K2-Signature");
                                    string MailContent_Request = "";
                                    string MailSubject_Request = "";
                                    string Email_Request = "";
                                    if (dto_mail != null)
                                    {
                                        MailContent_Request = dto_mail.ContentVN;
                                        MailContent_Request = MailContent_Request.Replace("$RequestDate$", DateTime.Now.ToShortDateString()).Replace("$Approver$", NextApproved);
                                        MailContent_Request = MailContent_Request.Replace("$url$", ConfigurationManager.AppSettings.Get("LinkStaffMovement") + hdfWorkingRecordID.Value);
                                        //MailContent_Request=cl_nextapprove.InsertImage(MailContent_Request,Server.MapPath(@"Images/logo.jpg"));
                                        MailSubject_Request = dto_mail.TitleVN;
                                    }

                                    bl_user = cl_user.FindById_BL(SessionManager.UserDomain);
                                    if (bl_user.DTO != null)
                                    {
                                        Email_Request = bl_user.Email;
                                    }
                                    #endregion

                                    #region Lấy thông tin gửi mail cho HR/HRP khi creator submitted
                                    dto_mail = cl_nextapprove.GetMailContentWithSignature("WR_CreatorToHR", "K2-Signature");
                                    
                                    string MailContent_HR = "";
                                    string MailSubject_HR = "";
                                    string Email_HR = "";
                                    string Email_HRP = "";
                                    if (dto_mail != null)
                                    {
                                        string EmpCode = ctrEmpInfo.EmpCode;
                                        string FullName = ctrEmpInfo.FullName;
                                        string cJobTitle = txtChucvu.Text.Trim();
                                        string cJobLevel = txtCapbac.Text.Trim();
                                        //Lấy thông tin phòng ban
                                        string cdept = "";
                                        string ndept = "";
                                        string njobtitle = "";
                                        string njoblevel = "";
                                        HIE_HierarchyBL bl_hie = new HIE_HierarchyBL();
                                        //Lấy thông tin phòng ban cũ
                                        bl_hie = cl_hie.SelectByID(Convert.ToInt64(fromhierarchy));
                                        if (bl_hie.DTO != null)
                                            cdept = bl_hie.NameVN;
                                        //Lấy thông tin phòng ban mới
                                        bl_hie = cl_hie.SelectByID(Convert.ToInt64(tohierarchy));
                                        if (bl_hie.DTO != null)
                                            ndept = bl_hie.NameVN;
                                        //End Lấy thông tin phòng ban

                                        //Lấy thông tin chức vụ mới

                                        LS_JobTitleBL bl_jobtitle = new LS_JobTitleBL();
                                        LS_JobTitleCollection cl_jobtitle = new LS_JobTitleCollection();
                                        LS_JobLevelBL bl_joblevel = new LS_JobLevelBL();
                                        LS_JobLevelCollection cl_joblevel = new LS_JobLevelCollection();
                                        bl_jobtitle = cl_jobtitle.SelectByID(Convert.ToInt64(cboJobTitle.SelectedValue));
                                        if (bl_jobtitle.DTO != null)
                                            njobtitle = bl_jobtitle.NameVN;
                                        bl_joblevel = cl_joblevel.SelectByID(Convert.ToInt64(cboJobLevel.SelectedValue));
                                        if (bl_joblevel.DTO != null)
                                            njoblevel = bl_joblevel.NameVN;

                                        //Lấy hình thức thay đôi
                                        string changeform = "";
                                        LS_ChangeFormBL bl_changeform = new LS_ChangeFormBL();
                                        LS_ChangeFormCollection cl_changeform = new LS_ChangeFormCollection();
                                        bl_changeform = cl_changeform.SelectByID(Convert.ToInt64(cboChangeForm.SelectedValue));
                                        if (bl_changeform.DTO != null)
                                            changeform = bl_changeform.NameVN;

                                        MailContent_HR = dto_mail.ContentVN;
                                        //Gán Employee code vào content
                                        MailContent_HR = MailContent_HR.Replace("$EmployeeCode$", EmpCode);
                                        //Gán FullName vào content
                                        MailContent_HR = MailContent_HR.Replace("$FullName$", FullName);
                                        //Gán current jobtitle
                                        MailContent_HR = MailContent_HR.Replace("$cJobTitle$", cJobTitle);
                                        //Gán current joblevel
                                        MailContent_HR = MailContent_HR.Replace("$cJobLevel$", cJobLevel);
                                        //Gán current dept
                                        MailContent_HR = MailContent_HR.Replace("$cDept$", cdept);
                                        //Gán new jobtitle
                                        MailContent_HR = MailContent_HR.Replace("$nJobTitle$", njobtitle);
                                        //Gán new joblevel
                                        MailContent_HR = MailContent_HR.Replace("$nJobLevel$", njoblevel);
                                        //Gán new dept
                                        MailContent_HR = MailContent_HR.Replace("$nDept$", ndept);
                                        //Gán hình thức thay đổi
                                        MailContent_HR = MailContent_HR.Replace("$Type$", changeform);

                                        //Gán Subject
                                        MailSubject_HR = dto_mail.TitleVN;
                                        //Gán phòng ban vào subject
                                        MailSubject_HR = MailSubject_HR.Replace("$Dept$", cdept);
                                        MailSubject_HR = MailSubject_HR.Replace("$Creator$", SessionManager.UserDomain);
                                    }

                                    //Gán email HR
                                    bl_user = cl_user.FindById_BL(colK2.GetUserOfHR());
                                    if (bl_user.DTO != null)
                                        Email_HR = bl_user.Email;

                                    //Gán email HRP
                                    string HRP = colK2.GetUserOfHRPLeader(ctrEmpInfo.EmployeeId);
                                    bl_user = cl_user.FindById_BL(HRP);
                                    if (bl_user.DTO != null)
                                        Email_HRP = bl_user.Email;

                                    // Add user CC
                                    List<string> listUserCC = new List<string>();
                                    listUserCC.Add(HRP);
                                    #endregion

                                    //End
                                    if (NextApproved != "")
                                    {
                                        int iTypeID = K2CoreLib.K2Utils.GetTypeIDProcessFromEfrom("HR_WorkingRecord");
                                        string sLinkContent = ConfigurationManager.AppSettings.Get("History_WR") + hdfWorkingRecordID.Value.Trim();
                                        string status = "0"; //(0: In process, 1: Complete, 2: Rework, 3:Reject)
                                        string eformid = K2CoreLib.K2Utils.submit2EForm(SessionManager.UserDomain, SessionManager.UserDomain, iTypeID, DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), sLinkContent, status, ctrEmpInfo.Username);

                                        string[] lst_eformid = eformid.Split(',');

                                        int proid = K2CoreLib.K2Utils.StartWordkingProcess(empid, workingrecordid, fromhierarchy, tohierarchy, hierarchyid,
                                                                                            NextApproved, MailContent_NextApprove, MailSubject_NextApprove, email_nextapprove,
                                                                                            MailContent_Request, MailSubject_Request, Email_Request, MailSubject_HR, MailContent_HR, Email_HR, Email_HRP, SessionManager.UserDomain, lst_eformid[1], lst_eformid[0],"",ctrEmpInfo.Username
                                                                                            ,ApproveLink,ViewHistoryLink,ExpireDay,ExpireAlert);

                                        cl.UpdateEform(Convert.ToInt64(hdfWorkingRecordID.Value), lst_eformid[1]);
                                        K2CoreLib.K2Utils.Update2EForm("0", lst_eformid[1], proid.ToString());

                                        #region begin to save history
                                        HR_WorkingRecordCollection cl_wr = new HR_WorkingRecordCollection();
                                        cl_wr.InsertHistory(Convert.ToInt64(hdfWorkingRecordID.Value), DateTime.Now, SessionManager.UserDomain, "Requester", "Submitted", "", 1, 0);

                                        //Insert CC (Reviewer) comment
                                        HistoryComment his = new HistoryComment();
                                        his.InsertReviewerComment(Convert.ToInt64(hdfWorkingRecordID.Value), listUserCC, 1);
                                        #endregion End save
                                    }

                                    #endregion
                                }
                                catch (Exception ex)
                                {
                                    List<long> id_del=new List<long>();
                                    id_del.Add(Convert.ToInt64(hdfWorkingRecordID.Value));
                                    cl.Delete(id_del);
                                    throw ex;
                                }

                                btnSubmit_Bot.Enabled = false;
                                btnSubmit_Top.Enabled = false;
                                //MessageBox.ShowByMessCode("10010");
                                ClientScript.RegisterStartupScript(Page.GetType(), "ClosePage", "ClosePage();", true);
                            }
                            else
                            {
                                MessageBox.ShowByMessCode("10632");
                            }
                        }
                        else
                        {
                            MessageBox.ShowByMessCode("12593");
                        }
                    }
                    else
                        MessageBox.ShowByMessCode("10224");
                }
                else
                {
                    MessageBox.ShowByMessCode("10095");
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        protected void btnRefresh_Top_Click(object sender, EventArgs e)
        {
            try
            {
                //ResetControl();
                //LoadWorkingRecordLast();
                //chkChangeSalary.Checked = false;
                Response.Redirect("HR_PopAddNewRotationHR1.aspx");
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        protected void cboOrgChart_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            try
            {
                HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();
                txtLeader_Now.Text = cl.ReturnLeader(Convert.ToInt64(cboOrgChart.SelectedValue == "" ? "0" : cboOrgChart.SelectedValue));
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        protected void cboProChart_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            /* Load Jobtitle theo JobChart và cấp bậc (đã bỏ)
            //Nếu cơ cấu quản lý đã chọn, không lọc theo cơ cấu chuyên môn
            if (
                string.IsNullOrEmpty(cboMgtChart.SelectedValue) == true
                || cboMgtChart.SelectedValue == HIE_HierarchyCollection.JobChartNullNodeValue
                )
            {
                this.PopulateJobTitle();
            }
             */
        }

        protected void cboMgtChart_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            /* Load Jobtitle theo JobChart và cấp bậc (đã bỏ)
            this.PopulateJobTitle();
             */
        }

        protected void cboJobTitle_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            try
            {
                long jobtitle = 0;
                long.TryParse(cboJobTitle.SelectedValue, out jobtitle);
                if (jobtitle > 0)
                {
                    PopulateJobTitle(jobtitle);
                    //Xóa rỗng combo Prochart và MgtChart
                    cboProChart.Items.Clear();
                    cboProChart.Items.Insert(0, new RadComboBoxItem("", ""));
                    cboProChart.SelectedIndex = 0;
                    cboMgtChart.Items.Clear();
                    cboMgtChart.Items.Insert(0, new RadComboBoxItem("", ""));
                    cboMgtChart.SelectedIndex = 0;
                    SetComboValue(cboProRanking, null, true);
                    SetComboValue(cboProGrade, null, true);
                    SetComboValue(cboMgtRaking, null, true);
                    SetComboValue(cboMgtGrade, null, true);

                    HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();
                    long subgroupid = cl.CheckJobTitle_SubGroup(jobtitle);
                    if (subgroupid > 0)
                    {
                        string prochartname = cl.GetProChartName(subgroupid);
                        string prochartid = cl.GetProChartID(subgroupid);

                        cboProChart.Items.Clear();
                        cboProChart.Items.Insert(0, new RadComboBoxItem(prochartname, prochartid));
                        cboProChart.SelectedIndex = 0;

                        rttProChart_input.Text = prochartname;
                    }

                    LS_JobTitleBL bl_tt = new LS_JobTitleBL();
                    LS_JobTitleCollection cl_tt = new LS_JobTitleCollection();
                    bl_tt = cl_tt.SelectLevelByTilte(jobtitle);
                    if (bl_tt.DTO != null)
                    {
                        cboJobLevel.DataBind();
                        SetComboValue(cboJobLevel, bl_tt.LevelId.ToString());
                    }
                    cboJobLevel_SelectedIndexChanged(null, null);
                }
                else
                {
                    cboProChart.Items.Clear();
                    cboProChart.Items.Insert(0, new RadComboBoxItem("", ""));
                    cboProChart.SelectedIndex = 0;
                    cboMgtChart.Items.Clear();
                    cboMgtChart.Items.Insert(0, new RadComboBoxItem("", ""));
                    cboMgtChart.SelectedIndex = 0;
                    SetComboValue(cboProRanking, null, true);
                    SetComboValue(cboProGrade, null, true);
                    SetComboValue(cboMgtRaking, null, true);
                    SetComboValue(cboMgtGrade, null, true);
                    SetComboValue(cboJobLevel, null, true);
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        protected void dtgTroCap_ItemDataBound(object sender, GridItemEventArgs e)
        {
            //try
            //{
            //    if (e.Item is GridDataItem)
            //    {
            //        GridDataItem item = (GridDataItem)e.Item;
            //        RadComboBox cbotrocap = (RadComboBox)item.FindControl("cboTroCap");

            //        cbotrocap.DataSourceID = dtsComboTrocap.ID;
            //        cbotrocap.DataBind();
            //        SetComboValue(cbotrocap, item["LSAllowanceID"].Text.Trim(), true);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
            //    MessageBox.Show(message);
            //}
        }

        //#region Kiểm tra các cấp phê duyệt đã có chưa, nếu chưa thì thông báo cho người sử dụng biết
        //public string CheckApprover()
        //{
        //    try
        //    {
        //        K2Collection col_k2=new K2Collection();
        //        string deptold = col_k2.GetDeptHeadOfHierarchy(Convert.ToInt64(txtOrgchartID.Text.Trim()));
        //        string deptnew = col_k2.GetDeptHeadOfHierarchy(Convert.ToInt64(cboOrgChart.SelectedValue));


        //    }
        //    catch (Exception ex)
        //    {
        //        AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
        //        MessageBox.Show(message);
        //    }
        //}
        //#endregion
    }
}